package com.qf.common.event.config;

import com.qf.common.event.consumer.IEventHandler;
import com.qf.common.event.consumer.RabbitMqListener;
import com.qf.common.event.utils.Contacts;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * 消费端的配置
 */
@Component
public class ConsumerConfiguration {

    /**
     * 获取微服务的名称
     */
    @Value("${spring.application.name}")
    private String queueName;

    /**
     * 声明交换机
     */
    @Bean
    public FanoutExchange getFanoutExchange(){
        return new FanoutExchange(Contacts.EXCHANGE_NAME, true, false);
    }

    /**
     * 声明消费端的队列
     * @return
     */
    @Bean
    public Queue getQueue(){
        return new Queue("queue-" + queueName, true);
    }

    /**
     * 队列和交换机的绑定
     * @param getQueue
     * @param getFanoutExchange
     * @return
     */
    @Bean
    public Binding getBinding(Queue getQueue, FanoutExchange getFanoutExchange){
        return BindingBuilder.bind(getQueue).to(getFanoutExchange);
    }

    /**
     * 注册RabbitMQ的事件监听器
     * @return
     */
    @Bean
    //如果Spring容器中，包含了IEventHandler类型的Bean，才会加载RabbitMQListener这个Bean
    @ConditionalOnBean(IEventHandler.class)
    public RabbitMqListener getRabbitMqListener(){
        System.out.println("RabbitMqListener已经装载！");
        return new RabbitMqListener();
    }
}
